<template>
  <!-- 选择用户 -->
  <a-modal v-model:visible="showEditUserDialog" :title="title" title-align="start" :on-before-ok="submitData" @cancel="closedDialog">
    <div style="min-height: 120px">
      <div class="flex-c">
        <p :style="`width: ${labelWidth}px; text-align: right; margin-right: 20px`">{{ label || title }}</p>
        <a-select v-model="users" :multiple="multiple" value-key="id" allow-search allow-clear style="width: 300px">
          <a-option v-for="(item, index) in userList" :key="index" :value="valueObj ? item : item.id">{{ item.userName }}</a-option>
        </a-select>
      </div>
    </div>
  </a-modal>
</template>

<script lang="ts">
  import { defineComponent, ref } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { getOrganizesUser } from '@/api/system'
  export default defineComponent({
    name: 'ChooseUser',
    props: {
      isShow: {
        type: Boolean,
        default: false,
      },
      title: {
        type: String,
        default: '添加用户',
      },
      valueObj: {
        type: Boolean,
        default: false,
      },
      label: {
        type: String,
        default: '选择用户',
      },
      labelWidth: {
        type: [Number, String],
        default: 120,
      },
      multiple: {
        type: Boolean,
        default: false,
      },
      defaultData: [String, Number, Array],
      isRequired: {
        type: Boolean,
        default: false,
      },
      list: {
        type: Array,
        default: () => [],
      },
    },
    emits: ['closed', 'success'],
    setup(props, { emit }) {
      const showEditUserDialog = ref(props.isShow)
      const users = ref<any>(props.defaultData)
      const userList = ref<Array<any>>([]) //用户列表
      // 获取用户列表
      async function getUserList() {
        if (props.list?.length) {
          userList.value = props.list
          return
        }
        const res: any = await getOrganizesUser({
          depart: false,
          pageNum: 1,
          pageSize: 1000,
        })
        userList.value = res?.data?.records || []
      }
      getUserList()
      // 关闭弹窗
      function closedDialog() {
        users.value = null
        emit('closed')
      }
      // 选择用户
      function submitData() {
        let hasVal = props.multiple ? users.value?.length > 0 : users.value ? true : false
        if (props.isRequired && !hasVal) {
          Message.error('请选择用户')
          return false
        }
        emit('success', users.value)
        closedDialog()
        return true
      }
      return {
        showEditUserDialog,
        closedDialog,
        submitData,
        userList,
        users,
      }
    },
  })
</script>
